<?php

/**
 * @version 1.0
 * @created 08-Jun-2009 3:16:46 PM
 */
class ReadBoard
{

	protected static $dataValidator;

	function __construct()
	{
	}

	/**
	 * 
	 * @param user
	 * @param mysqli
	 */
	public static function getBoardItems( array $urls, $itemLimit = 3, $useCahce = true, $cacheLocation = '../cache' )
	{
		$rssAtomSources = array();
		$twitterources = array();
		$returnArray = array();
		
		foreach( $urls as $feedSource ){
			if( $feedSource->type == FeedSource::RSS_SOURCE || $feedSource->type == FeedSource::ATOM_SOURCE ){
				array_push( $rssAtomSources, $feedSource );
			}else if( $feedSource->type == FeedSource::TWITTER_SOURCE ){
				array_push( $twitterources, $feedSource );
			}
		}
		if( count( $rssAtomSources ) > 0 ){
			$returnArray = array_merge($returnArray, ReadBoard::getAtomRSSItems( $rssAtomSources ) );
		}
		if( count( $twitterources ) > 0 ){
			$returnArray = array_merge($returnArray, ReadBoard::getTwitterFeeds( $twitterources ) );
		}
		//sort based on date/time
		usort($returnArray, "ReadBoard::sortByDateTime");
		return $returnArray;
	}
	
	protected static function getTwitterFeeds( array $feedSources ){

        if( count( $feedSources ) <= 0 ) return false;

        $curlInstances = array();//handle array
        $timelines = array();
        $returnArray = array();
		$curlMulti = curl_multi_init();
		
        foreach($feedSources as $feedSource){
                $curl = curl_init();
                curl_setopt( $curl, CURLOPT_URL, $feedSource->url );
                curl_setopt( $curl, CURLOPT_HEADER, 0 );
                curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );//return the image value
				curl_multi_add_handle($curlMulti, $curl);
				$curlInstance = new stdClass;
				$curlInstance->curl = $curl;
				$curlInstance->data = null;
                array_push( $curlInstances, $curlInstance );
        }
        
        $running = null;
		if( Cache::getInstance()->get("twitterFeeds") != false ){
			error_log("getting twitter feeds from cache", 0);
			foreach($curlInstances as $curlInstance){
					$info = curl_getinfo($curlInstance->curl);
	                $curlInstance->data = Cache::getInstance()->get($info['url']);
	                array_push( $timelines, $curlInstance->data );
	                curl_multi_remove_handle( $curlMulti, $curlInstance->curl );
	                $curlInstance->curl = null;
	        }
		}else{
			error_log("loading twitter feeds from source", 0);
			 do{
        		curl_multi_exec($curlMulti, $running);
	        }while($running > 0);
	
	        // get the result and save it in the result ARRAY
	        foreach($curlInstances as $curlInstance){
	                $curlInstance->data = json_decode( curl_multi_getcontent( $curlInstance->curl ) );
	                $info = curl_getinfo( $curlInstance->curl );
	                Cache::getInstance()->add($info['url'], $curlInstance->data, false, 900);
	                array_push( $timelines, $curlInstance->data );
	                curl_multi_remove_handle( $curlMulti, $curlInstance->curl );
	                $curlInstance->curl = null;
	        }
	        Cache::getInstance()->add("twitterFeeds", true, false, 900);
	        curl_multi_close($curlMulti);
		}
        
        $combinedTweets = array();
		$count = 1;
		
		foreach( $timelines as $obj ){
			$tweets = $obj;
			//some timelines don't return a top level array with all the tweets, so we check for this
			if( $obj->{'timeline'} ){
				$tweets = $obj->{'timeline'};
			}
			foreach( $tweets as $tweet){
				if( $tweet->{'retweeted_status'} != null ){
					$tweet = $tweet->{'retweeted_status'};
				}
				//echo $count;
				$combinedTweets[$tweet->{'id_str'}] = $tweet;
				$count += 1;
			}
		}
		
		foreach($combinedTweets as $tweet){
			$boardItem = new BoardItem();
			$boardItem->type = BoardItem::TWITTER;
			$boardItem->image = $tweet->{'user'}->{'profile_image_url'};
			$boardItem->text = $tweet->{'user'}->{'screen_name'} . ": " . $tweet->{'text'};
			$boardItem->url = $tweet->{'user'}->{'url'};
			$boardItem->date = strtotime( $tweet->{'created_at'} );
			$boardItem->source = $tweet->{'user'}->{'screen_name'};
			//add entities if they exist
			if( $tweet->{'entities'}->{'media'} != null ){
				foreach($tweet->{'entities'}->{'media'} as $img){
					$entity = new TwitterEntity();
					$entity->url = $img->{'media_url'};
					$entity->width = $img->{'sizes'}->{'thumb'}->{'w'};
					$entity->height = $img->{'sizes'}->{'thumb'}->{'h'};
					array_push( $boardItem->entities, $entity );
				}
			}
			//add the item
			array_push( $returnArray, $boardItem );
		}

        return $returnArray;
	} 
	
	protected static function sortByDateTime($a, $b)
	{
	    if ( $a->date == $b->date ){
	        return 0;
	    }
	    return ( $a->date > $b->date ) ? -1 : 1;
	}
	
	protected static function getAtomRSSItems( array $feedSources, $itemLimit = 3, $useCahce = true, $cacheLocation = 'libs/dao/cache' ){
		$returnArray = array();
		$urls = array();
	 	foreach($feedSources as $feedSource){
	 		array_push( $urls, $feedSource->url );
        }
		if( Cache::getInstance()->get("rssFeeds") != false ){
			error_log("getting rss from cache", 0);
			return Cache::getInstance()->get("rssFeeds");
		}
		error_log("getting rss from source", 0);
		$feed = new SimplePie();
		$feed->set_item_limit( $itemLimit );
		$feed->enable_cache( $useCahce );
		$feed->cache_location = $ROOT . $cacheLocation;
		$feed->set_feed_url( $urls );
		/*
		 * not sure why we need this, won't the browser cache images
		// When we set these, we need to make sure that the handler_image.php file is also trying to read from the same cache directory that we are.
		$feed->set_favicon_handler('handler_image.php');
		$feed->set_image_handler('handler_image.php');
		*/
		// Initialize the feed.
		$feed->init();
		
		// Make sure the page is being served with the UTF-8 headers.
		$feed->handle_content_type();
		
		if( $feed->error() ){
			throw new Exception('SimplePie error: ' . $feed->error());
		}
		foreach($feed->get_items() as $item){
			$boardItem = new BoardItem();
			$boardItem->type = BoardItem::RSS;
			$boardItem->title = $item->get_title();
			$boardItem->text = $item->get_description();
			$boardItem->url = urldecode( $item->get_permalink() );
			$boardItem->date = $item->get_date('j M Y | g:i a');
			$boardItem->source = urldecode( $feed->get_permalink() );
			if ($enclosure = $item->get_enclosure()){
				$boardItem->enclosure = $enclosure->native_embed( array('mediaplayer' => 'for_the_demo/mediaplayer.swf') );
			}
			array_push( $returnArray, $boardItem );
		}
		Cache::getInstance()->add("rssFeeds", $returnArray, false, 86400);
		return $returnArray;
	}

}
?>